<template>
  <div class="system-role-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="40%" @close="closeDialog" :close-on-click-modal="false">
      <el-form ref="dialogFormRef" :model="state.formItem.addItem" :rules="state.rules" size="default" label-width="100px"
        v-loading="state.dataLoading" label-position="right" style="width: 90%;text-align: center;">
        <el-form-item label="任务名称" prop="task_name">
          <el-input v-model="state.formItem.addItem.task_name" placeholder="请输入指标名称" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="指标名称" prop="name">
          <el-input v-model="state.formItem.addItem.name" placeholder="请输入指标名称" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="参考信源" prop="refer">
          <el-input  type="textarea"  v-model="state.formItem.addItem.refer" placeholder="请输入参考信源" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="参考指南" prop="guide">
          <el-input type="textarea"  v-model="state.formItem.addItem.guide" placeholder="请输入参考指南" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="信源类型" prop="refer_type">
          <el-select v-model="state.formItem.addItem.refer_type" placeholder="请选择信源等级">
            <el-option label="官网/政府" value="1"></el-option>
            <el-option label="权威媒体" value="2"></el-option>
            <el-option label="其他可信信源" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" :prop="'dynamicItem.' + index+ '.name'" v-for="(item, index) in state.formItem.dynamicItem" :key="index">
          <el-input v-model="item.name" placeholder="请输入标题" clearable style="width: 30%;" :disabled="true"></el-input>
          <div style="width: 10%;">内容:</div>
          <el-input v-model="item.value" placeholder="请输入标题对应的值" clearable style="width: 60%;" :disabled="true"></el-input>
        </el-form-item>
        <el-divider><span style="color: #F56C6C;">用户需填写区域</span></el-divider>
        <el-form-item label="标题" :prop="'userFilled.' + index+ '.name'" v-for="(item, index) in state.formItem.userFilled" :key="index">
          <el-row style="width: 100% !important;">
              <el-col :span="7">
                <el-input v-model="item.name" placeholder="请输入标题" clearabl :disabled="true"></el-input>
              </el-col>
              <el-col :span="2">
                <span style="color: red;" v-if="item.radio==1">*</span>内容:
              </el-col>
              <el-col :span="13">
                <el-input v-model="item.value" placeholder="请填写内容"  required></el-input>
              </el-col>
              <el-col :span="2">
                <span style="color: red;" v-if="item.radio==1">必填</span>
              </el-col>
            </el-row>
            <el-row style="width: 100% !important; margin-left: -8%; margin-top: 10 !important;">
              <el-col :span="2">
                <div>备注:</div>
              </el-col>
              <el-col :span="22">
                <el-input v-model="item.remark" placeholder="请输入备注(选填)" clearabl :disabled="true"></el-input>
              </el-col>
            </el-row>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="state.formItem.addItem.remark" placeholder="请输入备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="网页截图">
          <div style="border: 1px solid #ccc; width: 100%;">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 300px; overflow-y: hidden;"
            v-model="state.formItem.editorContent"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
        </el-form-item>
        <el-form-item label="是否可采集:" prop="state.not_collectible">
          <template  #default="scope">
							<span style="color: #F56C6C" v-if="state.not_collectible==1" effect="plain" size="small">{{state.not_collectible_remarks}}</span>
							<span style="color: #909399" v-else  effect="plain" size="small">是</span>
						</template>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row style="width: 100% !important;">
          <el-col :span="12">
            <span class="dialog-footer">
              <el-col :span="20">
                <el-input v-model="state.notCollectibleData.reason" placeholder="请输入不可采集原因" clearable></el-input><el-button type="warning" :loading="state.btnLoading" @click="notCollectible()" size="danger">不可采集</el-button>
              </el-col>
            </span>
          </el-col>
          <el-col :span="12">
            <span class="dialog-footer">
              <el-button @click="closeDialog()" size="default">取 消</el-button>
              <el-button type="primary" :loading="state.btnLoading" @click="onSubmit(dialogFormRef)"
                size="danger">提交</el-button>
            </span>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="systemRoleDialog">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { claimTasksApi } from '/@/api/claimTasks'
import { ElMessage } from 'element-plus';
import { getUploadUrl } from "/@/utils/getHost.js";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogFormRef = ref();
const router = useRouter();
const state = reactive({
  userId: null,
  index:0,
  userIndex:0,
  apiData: {
		id:'',
	},
  rules: {
    refer_type: [{ required: true, message: '请输入选择信源类型', trigger: 'blur' }],
  },
  dialog: {
    isShowDialog: false,
    title: '',
    submitTxt: '',
  },
  notCollectibleData:{
      id:'',
      reason:'',
  },
  dataLoading: false,
  btnLoading: false,
  // 填写内容及自定义文本框
  formItem: {
        addItem:{
          refer_type:'',
          id:'',
        },
        dynamicItem: [
        //默认显示一条
          // {
          //   name: '',
          //   value:''
          // }
        ],
        userFilled: [
        //默认显示一条
          // {
          //   name: '',
          //   radio:'1',
          // }
        ],
        editorImgList:[], // 富文本里的内容
        editorContent:'', // 富文本所有内容
        not_collectible:'',
        not_collectible_remarks:'',
  }
});

// 打开弹窗
const openDialog = (data) => {
  state.dialog.isShowDialog = true;
  state.dialog.title = '指标详情';
  state.apiData.id = data.id;
  state.formItem.addItem.norm_receive_id = data.id;
  state.notCollectibleData.id = data.id
  // 清空数据
  
  claimTasksApi().normReceivesDetail(state.apiData).then(res => {
		let addItem = res.data.addItem;
    let userFilled = res.data.userFilled;
    let adminFilled = res.data.adminFilled;
    // 数据详情
    state.formItem.addItem.task_id = addItem.task_id;
    state.formItem.addItem.norm_id = addItem.norm_id;
    state.formItem.addItem.norm_list_id = addItem.id;
    state.formItem.addItem.name = addItem.name;
    state.formItem.addItem.task_name = addItem.task_name;
    state.formItem.addItem.refer = addItem.refer;
    state.formItem.addItem.guide = addItem.guide;
    state.not_collectible_remarks = data.not_collectible_remarks
    state.not_collectible = data.not_collectible
    //富文本内容相关
    
    if(res.data.normCollectInfo)
    {
      let normCollectInfo = res.data.normCollectInfo;
      state.formItem.addItem.refer_type = normCollectInfo.refer_type;
      state.formItem.addItem.remark = normCollectInfo.remark;
      if(normCollectInfo.editorContent){
        state.formItem.editorContent = normCollectInfo.editorContent
      }else{
        state.formItem.editorContent = '请输入截图'
      }
    }

    state.userIndex = 0;
    state.index = 0;
    console.log(state.formItem.addItem)
    userFilled.forEach(item => {
          state.formItem.userFilled.push({id:item.id,name:item.extend_name,radio:item.required+"",value:item.extend_value});
          state.userIndex++
		});
    adminFilled.forEach(item => {
          state.formItem.dynamicItem.push({id:item.id,name:item.extend_name,value:item.extend_value,});
          state.index++
		});
	}).catch(() => {

	})
};

// 数据不可采集
const notCollectible = () =>{
  const editor = editorRef.value;
  if(state.notCollectibleData.id ==""){
    ElMessage.error('无法获取ID!');
    return;
  }
  if(state.notCollectibleData.reason ==""){
    ElMessage.error('请填写不可采集的原因!');
    return;
  }
  claimTasksApi().notCollectible(state.notCollectibleData).then(res => {
        const editor = editorRef.value;
        // 获取富文本里的图片地址
        editor.getElemsByType("image").forEach((item, index) => {
          state.formItem.editorImgList.push(item.src);
        })
        state.formItem.editorContent = editor.getHtml() // 获取富文本内容
        let apiIndex = 1;
            if(state.formItem.editorImgList.length>2){
                    apiIndex++;
                    state.formItem.editorImgList = [];
                    ElMessage.error('只允许上传两张图片!');
            }
            if(apiIndex==1&&valid){
              claimTasksApi().normReceivesModify(JSON.stringify(state.formItem)).then(res => {
                editor.clear()
              state.btnLoading = false
              ElMessage.success('操作成功');
              closeDialog();
              emit('refresh'); 
              }).catch(() => {
                editor.clear()
                state.btnLoading = false
              closeDialog();
              emit('refresh');
              }) 
            }
  }).catch(() => {
      editor.clear()
      state.btnLoading = false
      closeDialog();
      emit('refresh');
  })
  state.notCollectibleData.reason = '';
}

// 提交
const onSubmit = () => {
  const editor = editorRef.value;
  // 获取富文本里的图片地址
  editor.getElemsByType("image").forEach((item, index) => {
    state.formItem.editorImgList.push(item.src);
	})
  state.formItem.editorContent = editor.getHtml() // 获取富文本内容
  dialogFormRef.value.validate((valid, fields) => {
    let userFilledInfo = state.formItem.userFilled;
      let apiIndex = 1;
      for(let i=0;i<userFilledInfo.length;i++)
      {
        if (userFilledInfo[0].radio==1) {
            if (userFilledInfo[0].value == "") {
              apiIndex++;
              ElMessage.error('请填写红色星号必填项!');
              break;
            }
        }
      }
      console.log(state.formItem.editorImgList)
      if(state.formItem.editorImgList.length>2){
              apiIndex++;
              state.formItem.editorImgList = [];
              ElMessage.error('只允许上传两张图片!');
      }
      if(apiIndex==1&&valid){
        claimTasksApi().normReceivesModify(JSON.stringify(state.formItem)).then(res => {
          editor.clear()
         state.btnLoading = false
         ElMessage.success('操作成功');
         closeDialog();
         emit('refresh'); 
        }).catch(() => {
          editor.clear()
          state.btnLoading = false
         closeDialog();
         emit('refresh');
        }) 
      }
  })
};

// 关闭弹窗
const closeDialog = () => {
  state.index=0
  state.userIndex=0
  state.formItem.addItem.task_id = '';
  state.formItem.addItem.norm_id = '';
  state.formItem.addItem.norm_list_id = '';
  state.formItem.addItem.name = '';
  state.formItem.addItem.task_name = '';
  state.formItem.addItem.refer = '';
  state.formItem.addItem.refer_type = '';
  state.formItem.addItem.remark = '';
  state.formItem.addItem.guide = '';
  state.formItem.dynamicItem = [];
  state.formItem.userFilled = [];
  state.formItem.editorImgList = [];
  state.formItem.editorContent = ''; 
  state.not_collectible_remarks = ''
  state.not_collectible = ''
  if(state.formItem.addItem.refer_type){
    state.formItem.addItem.refer_type ='';
  }
  if(state.formItem.addItem.remark)
  {
    state.formItem.addItem.remark = '';
  }
  dialogFormRef.value.resetFields();
  state.dialog.isShowDialog = false;
};


// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
const toolbarConfig = {}
const editorConfig = { 
  placeholder: '请输入截图',
  MENU_CONF: {}
 }
editorConfig.MENU_CONF['uploadImage'] = {
    // 其他配置...

    // 小于该值就插入 base64 格式（而不上传），默认为 0
    base64LimitSize: 5 * 1024, // 5kb
    server: getUploadUrl(),
    fieldName: 'file',
    // 单个文件上传成功之后
    onSuccess(file, res) {          // JS 语法
        console.log(`${file.name} 上传成功`, res)
    },

    // 单个文件上传失败
    onFailed(file, res) {           // JS 语法
        console.log(`${file.name} 上传失败`, res)
    },

    // 上传错误，或者触发 timeout 超时
    onError(file, err, res) {               // JS 语法
        console.log(`${file.name} 上传出错`, err, res)
    },
}
onMounted(() => {
  if(router.currentRoute.value.query.task_id){
		state.formItem.addItem.task_id = router.currentRoute.value.query.task_id
	}

});

  // 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.el-dialog__body {
 
  display: flex;

  justify-content: center;

  align-content: center;

}
.el-input.is-disabled{
  background:#fff !important;
  color: var(--el-radio-text-color) !important;
  -webkit-text-fill-color: var(--el-radio-text-color) !important;
}
:deep(.el-input .el-input__inner){
  background:#fff !important;
  color: var(--el-radio-text-color) !important;
  -webkit-text-fill-color: var(--el-radio-text-color) !important;
}
:deep(.el-input .el-input__wrapper){
  background:#fff !important;
  color: var(--el-radio-text-color) !important;
  -webkit-text-fill-color: var(--el-radio-text-color) !important;
}
.el-textarea.is-disabled{
    background:#fff !important;
    color: var(--el-radio-text-color) !important;
    -webkit-text-fill-color: var(--el-radio-text-color) !important;
  }
  :deep(.el-textarea .el-textarea__inner){
    background:#fff !important;
    color: var(--el-radio-text-color) !important;
    -webkit-text-fill-color: var(--el-radio-text-color) !important;
  }
  :deep(.el-textarea .el-textarea__wrapper){
    background:#fff !important;
    color: var(--el-radio-text-color) !important;
    -webkit-text-fill-color: var(--el-radio-text-color) !important;
  }
</style>
